import { truthy } from '@gnlab/utils'
import { Button, Input, message } from 'antd'
import { EditModal } from '@/desktop/components'
import services from '@/services'

/**
 * 显示通过名片加好友的对话框
 */
export default function ApplyByPersonCard(props: {
  senderWxid?: string // 消息发送者的 wxid
  personCardUserId?: string // 名片中的 userId
  onFinish: () => void
}) {
  const { senderWxid, personCardUserId, onFinish } = props
  const open = truthy(senderWxid) && truthy(personCardUserId)
  return <EditModal open={open} title="发送好友申请" width="500px" onCancel={onFinish}>
    {open ? (
      <Content senderWxid={senderWxid} personCardUserId={personCardUserId} onFinish={onFinish} />
    ) : null}
  </EditModal>
}

function Content(props: { senderWxid: string; personCardUserId: string; onFinish: () => void }) {
  const { senderWxid, personCardUserId, onFinish } = props
  const [applyMessage, setApplyMessage] = useState('')

  const [sending, setSending] = useState(false)
  async function send() {
    const contact = services.contacts.current.contact.value
    if (!contact) return void onFinish()

    setSending(true)
    const res = await services.chat.applyByPersonCard({
      wxid: contact.ownerWxid,
      conversationId: contact.conversationId,
      senderWxid,
      personCardUserId,
      message: applyMessage,
    })
    if (res.success) {
      void message.success('已发送好友申请')
      onFinish()
    } else {
      void message.warning(res.error)
    }
  }

  return <>
    <main css={style}>
      <div>输入好友验证消息：</div>
      <Input.TextArea
        rows={5}
        placeholder="不超过 50 个汉字"
        maxLength={50}
        showCount
        value={applyMessage}
        onChange={e => setApplyMessage(e.target.value)}
      />
    </main>
    <footer>
      <Button type="primary" onClick={send} loading={sending} disabled={!applyMessage.length}>
        发送
      </Button>
    </footer>
  </>
}

const style = css`
  padding: 6px 24px 20px !important;

  .ant-input-affix-wrapper {
    margin-top: 8px;
  }
  textarea {
    margin: 8px 0;
  }

  a {
    margin-right: 8px;
  }
`
